const inquirer = require("inquirer");
const fs = require("fs");
const COMPREIFX = "yqd-";
const componentDir = './src/components/'
const log = console.log;
const changeColor = (str, color = 93) => `\x1b[${color}m${str}\x1b[0m`;
const { jsFile, vueFile } = require("./file/preset.js");
const { writeComponentsFile } = require('./write')
const {updateDevFile} = require('./writeDev')
log(changeColor("创建组件", 92));

const createComponent = (option, createDev) => {
  const { cType, cName } = option;
  log("创建组件");
  log(`类型：${cType} 名称：${cName}`);
  createCom(cType, cName, createDev);
};

const readCom = (type, name) => {
  const files = fs.readdirSync(`${componentDir}${type}/`);
  return files.includes(`${COMPREIFX}${name}`);
};


const createCom = async (type, name, createDev) => {
  try {
    const dirName = `${componentDir}/${type}/${COMPREIFX}${name}`;
    const DevDir = __dirname
    const makeDir = fs.mkdirSync(dirName);
    const writeVue = fs.writeFileSync(
      `${dirName}/index.js`,
      jsFile(type, name)
    );
    const writeJS = fs.writeFileSync(
      `${dirName}/index.vue`,
      vueFile(name)
    );
    const writeComponent = writeComponentsFile(type, `${COMPREIFX}${name}`)
    let updateDevFileFlag = undefined
    if (createDev) {
      updateDevFileFlag = await updateDevFile(type,`${COMPREIFX}${name}`)
    }
    if (!makeDir && !writeVue && !writeJS && !writeComponent && !updateDevFileFlag) log(changeColor("创建成功", 92));
  } catch (error) {
    throw new Error(error);
  }
};

const comInfo = {
  cType: "",
  cName: "",
};
const init = inquirer
  .prompt([
    {
      type: "list",
      name: "comType",
      message: "组件类型:",
      default: 0,
      choices: [
        { value: "basic", name: "basic" },
        { value: 'business', name: 'business' },
        { value: "cus-form", name: "cus-form" },
        { value: 'other', name: 'other' },
        { value: 'only', name: 'only' },
      ],
    },
    {
      type: "input",
      name: "comName",
      message: "组件名称(yqd-):",
      when(val) {
        comInfo.cType = val.comType;
        return true;
      },
      validate: (val) => {
        comInfo.cName = val;
        if (readCom(comInfo.cType, `${comInfo.cName}`)) {
          log(changeColor("\n存在同类型的重名组件！"));
          return false;
        }
        return !!val;
      },
    },
    {
      type: "list",
      name: "create2dev",
      message: "创建在开发Demo中？",
      default: 0,
      choices: [
        { value: true, name: "Y" },
        { value: false, name: 'N' }
      ],
    }
  ])
  .then(({ create2dev }) => {
    createComponent({ cType: comInfo.cType, cName: `${comInfo.cName}` }, create2dev);
  })
  .catch((error) => {
    log(error);
  });
